package net.gazhi.delonix.rbac.service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import net.gazhi.delonix.core.annonation.ApiLevel;
import net.gazhi.delonix.core.jpa.AbstractEntityService;
import net.gazhi.delonix.rbac.entity.Action;
import net.gazhi.delonix.rbac.entity.Role;
import net.gazhi.delonix.rbac.form.RoleEditForm;
import net.gazhi.delonix.rbac.thread.RBACThreadContext;

@Service
public class RoleService extends AbstractEntityService<Role> {

	@Autowired
	private ActionService actionService;

	/**
	 * 列出所有 Action
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Role> listAll() {
		return (List<Role>) createCriteria().addOrder(Order.asc("id")).list();
	}

	@Transactional
	public void save(RoleEditForm form, BindingResult result) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", form.getName());
		if (this.existedOther(form.getId(), params)) {
			result.reject("RoleEditForm.name", "角色名称重复！");
			return;
		}
		Role role = form.getId() > 0 ? this.get(form.getId()) : new Role();
		if (role == null) {
			result.reject("RoleEditForm.id.notfound", "角色不存在（id=" + form.getId() + "）！");
			return;
		}
		Timestamp now = new Timestamp(System.currentTimeMillis());
		role.setName(form.getName());
		role.setRemark(form.getRemark());
		role.setUpdateTime(now);
		role.setUpdatedBy(RBACThreadContext.getLoginUser().getLoginName());
		if (role.getId() == 0) {
			role.setCreateTime(now);
			role.setCreatedBy(RBACThreadContext.getLoginUser().getLoginName());
		}
		role.getActions().clear();
		if (form.getActionIds() != null && form.getActionIds().length > 0) {
			for (int actionId : form.getActionIds()) {
				Action act = this.actionService.get(actionId);
				if (act == null) {
					result.reject("RoleEditForm.actionIds.notfound", "功能点不存在（actionId=" + actionId + "）！");
					return;
				}
				// 忽略其他等级的功能点
				if (act.getLevel() == ApiLevel.GRANT_REQUIRED.value()) {
					role.getActions().add(act);
				}
			}
		}
		dao.saveOrUpdate(role);
	}

	@Transactional
	public void delete(Integer id, BindingResult result) {
		if (result.hasErrors()) {
			return;
		}
		Role role = super.get(id);
		if (role == null) {
			result.reject("roleId.notfound", "角色不存在！");
			return;
		}
		dao.delete(role);
	}
}
